<?php

namespace app\admin\service;

use app\admin\lib\exception\BaseException;
use app\admin\model\Login as LoginModel;

class LoginService extends BaseService
{

    /**
     * 管理员登录
     */
    public function login(array $data)
    {
        $admin = LoginModel::findByUsername($data['username']);

        // 校验用户是否存在
        if (!$admin) {
            throw new BaseException([
                'code' => 400,
                'message' => '用户名不存在',
                'errorCode' => 10001
            ]);
        }

        // 校验密码
        if (!$admin->verifyPassword($data['password'])) {
            throw new BaseException([
                'code' => 400,
                'message' => '密码错误',
                'errorCode' => 10002
            ]);
        }

        // 校验账号状态
        if ($admin['status'] !== 1) {
            throw new BaseException([
                'code' => 400,
                'message' => '该账号已被禁用，请联系管理员',
                'errorCode' => 10003
            ]);
        }

        // 记录登录时间
        $admin->updateLoginTime();

        // 生成令牌
        $tokenData = $this->getAuthService()->generateLoginToken($admin->toArray());

        return [
            'user_info' => $admin->toArray(),
            'token' => $tokenData['token'],
            'expire' => $tokenData['expire']
        ];
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo(int $userId)
    {
        $admin = LoginModel::findById($userId);

        if (!$admin) {
            throw new BaseException([
                'code' => 404,
                'message' => '用户不存在',
                'errorCode' => 10006
            ]);
        }

        $userInfo = $admin->toArray();
        unset($userInfo['password']);

        return [
            'user_info' => $userInfo
        ];
    }

    /**
     * 用户修改个人信息
     */
    public function editSelf(int $currentUserId, array $requestData)
    {
        // 清理空值，避免把空字符串提交到模型
        $requestData = array_filter($requestData, function ($v) {
            return !(is_null($v) || $v === '');
        });

        $user = LoginModel::findById($currentUserId);
        if (!$user) {
            throw new BaseException([
                'code' => 404,
                'message' => '用户不存在或已删除',
                'errorCode' => 70002
            ]);
        }

        // 检查用户名唯一性
        if (isset($requestData['username']) && $requestData['username'] != $user->username) {
            $exists = LoginModel::checkUsernameExists($requestData['username'], $currentUserId);
            if ($exists) {
                throw new BaseException([
                    'code' => 400,
                    'message' => '用户名已被占用',
                    'errorCode' => 70003
                ]);
            }
        }

        // 检查邮箱唯一性
        if (isset($requestData['email']) && $requestData['email'] != $user->email) {
            $exists = LoginModel::checkEmailExists($requestData['email'], $currentUserId);
            if ($exists) {
                throw new BaseException([
                    'code' => 400,
                    'message' => '邮箱已被注册',
                    'errorCode' => 70004
                ]);
            }
        }

        // 检查手机号唯一性
        if (isset($requestData['phone']) && $requestData['phone'] != $user->phone) {
            $exists = LoginModel::checkPhoneExists($requestData['phone'], $currentUserId);
            if ($exists) {
                throw new BaseException([
                    'code' => 400,
                    'message' => '手机号已被注册',
                    'errorCode' => 70005
                ]);
            }
        }

        $result = $user->updateUserInfo($requestData);
        if (!$result) {
            throw new BaseException([
                'code' => 500,
                'message' => '信息更新失败，请重试',
                'errorCode' => 70006
            ]);
        }

        return [
            'user_info' => $user->toArray()
        ];
    }

    /**
     * 用户退出登录
     */
    public function logout(string $token)
    {
        $this->getAuthService()->verifyToken($token);
        $this->getAuthService()->addToBlacklist($token);
        return true;
    }
}
